﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace ObjectModel.Excel
{
    /// <summary>
    /// An Excel range object that can resolve itself from serializable info.
    /// </summary>
    public class ResolvableLiteralRange : ResolvableRange
    {
        Application App { get { return Globals.Application; } }

        public override ResolvableWorkbook Workbook { get; set; }

        public string AddressWithSheetName { get; set; }

        public ResolvableLiteralRange() { } // Parameterless constructor required for serialization.

        public ResolvableLiteralRange(Range rng)
        {
            Workbook = new ResolvableWorkbook(rng.GetWorkbook());
            AddressWithSheetName = rng.GetAddressWithSheetName();
        }

        public override Range Resolve()
        {
            //_Workbook prevActiveWorkbook = mApp.ActiveWorkbook;
            //bool prevScreenUpdatingSetting = mApp.ScreenUpdating;
            //mApp.ScreenUpdating = false;
            bool prevScreenUpdatingSetting = App.ScreenUpdating;
            App.ScreenUpdating = false;

            try
            {
                ((_Workbook)Workbook.Resolve()).Activate();
                return GetRangeFromAddress();
            }
            catch (COMException)
            {
                throw;
            }
            finally
            {
                //prevActiveWorkbook.Activate();
                App.ScreenUpdating = prevScreenUpdatingSetting;
            }
        }

        Range GetRangeFromAddress()
        {
            try { return App.Range[AddressWithSheetName]; }
            catch (COMException)
            {
                throw new InvalidOperationException("Could not resolve range from literal reference.");
            }
        }
    }
}
